print('------')
from mpython import *
import os
import time  # 加入时间模块
import urequests as requests
import network
wifi = wifi()

print('installer.py')

wifi_connection = 0
wifi_name = 'WIFI名称'
wifi_password = 'WIFI密码'

print('系统安装中…')

def cata_maker(path): #   系统目录创建工具
    try:
        # 尝试打开目录，如果不存在会抛出OSError异常
        os.stat(path)
    except OSError:
        # 目录不存在，创建目录
        try:
            os.mkdir(path)
        except OSError as e:
            print("创建目录时发生错误：{}".format(e))

# 尝试创建目录
cata_maker('Teno_Brain/KITS')
print("系统加载中：1/15)
ensure_dir_exists('Teno_Brain/Storage')
print("系统加载中：2/15)
ensure_dir_exists('tools')
print("系统加载中：3/15)

# 写入配置文件
with open('Teno_Brain/Storage/config.tnt', 'w') as conf:
    conf.write("WiFi:{}\nPassword:{}".format(wifi_name, wifi_password))
print("系统加载中：4/15)
with open('Teno_Brain/Storage/TENO.tnt', 'w') as te:
    te.write('')
print("系统加载中：5/15)

max_retries = 5
retry_count = 0

while wifi_connection == 0 and retry_count < max_retries:
    print('正在连接网络...')
    wifi.connectWiFi(wifi_name, wifi_password)
    time.sleep(2)  # 等待连接完成
    wifi_connection = 1
    print('网络连接成功！')
    urls = [
        ('https://gitee.com/ttacode/Teno/raw/master/Teno/boot.py', 'boot.py'),
        ('https://gitee.com/ttacode/Teno/raw/master/Teno/tools/kenny_desclock.py', 'tools/kenny_desclock.py'),
        ('https://gitee.com/ttacode/Teno/raw/master/Teno/tools/kenny_toolswitcher.py', 'tools/kenny_toolswitcher.py'),
        ('https://gitee.com/ttacode/Teno/raw/master/Teno/Teno_Brain/KITS/UI.py', 'Teno_Brain/KITS/UI.py'),
        ('https://gitee.com/ttacode/Teno/raw/master/Teno/Teno_Brain/RSaD.py', 'Teno_Brain/RSaD.py'),
        ('https://gitee.com/ttacode/Teno/raw/master/Teno/Teno_Brain/SPoF.py', 'Teno_Brain/SPoF.py'),
        ('https://gitee.com/ttacode/Teno/raw/master/Teno/Teno_Brain/TENO.py', 'Teno_Brain/TENO.py'),
        ('https://gitee.com/ttacode/Teno/raw/master/Teno/Teno_Brain/dice.py', 'Teno_Brain/dice.py'),
        ('https://gitee.com/ttacode/Teno/raw/master/Teno/Teno_Brain/pivot.py', 'Teno_Brain/pivot.py')
    ]
    for i, (url, filepath) in enumerate(urls, start=1):
        response = requests.get(url)
        if response.status_code == 200:
          with open(filepath, 'w') as file:
               file.write(response.text)
        print("系统加载中：{}/15".format(i+5))
    print("系统加载中：15/15)
    print('Teno启动成功')
    machine.reset()
retry_count += 1

if wifi_connection == 0:
    print("无法连接到WiFi，请检查网络配置")
